package servlet;

import utils.string.session.SessionStringUtil;
import vo.Equipment;
import vo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class LoginServlet extends HttpServlet {
    //该对象是进行登录的判断，获取listener传递的数据然后进行验证判断
    private  Boolean EXITS_FLAG = false;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        //获取index中的数据传递
        String name = req.getParameter("account");
        String password = req.getParameter("password");
        String authority = req.getParameter("authority");
        int auth_id = Integer.valueOf(authority);
        //进行数据的判断
        HashMap users = (HashMap) session.getAttribute(SessionStringUtil.ALL_USERS);
        Set set = users.keySet();
        Iterator ite = set.iterator();
        User user = null;
        boolean author_same = false;
        //判断
        exits:
        while (ite.hasNext()) {
            int user_id = (int) ite.next();
            user = (User) users.get(user_id);
            EXITS_FLAG = judge(user, name, password);
            if (EXITS_FLAG){
                if(auth_id == user.getAuth_id()){
                    author_same = true;
                }
                break exits;
            }
        }
        if(EXITS_FLAG && author_same){
            req.getSession().setAttribute(SessionStringUtil.USER,user);
            if (auth_id == 1){
                resp.sendRedirect("/equipmentManager_war_explode/manageAllEquipments.jsp");//管理界面
            }
            else{
                resp.sendRedirect("/equipmentManager_war_explode/manageUserEquipments.jsp");//普通用户界面
            }
        }else{
            resp.sendRedirect("/equipmentManager_war_explode/loginFault.jsp");
        }
    }


    private Boolean judge(User user, String name, String password) {
        if(user.getUser_name().equals(name) && user.getUser_password().equals(password))
            return true;
        return false;
    }
}